<template>
  <div class="page flex flex-row gap-x-3 p-3 h-dvh">
    <div class="w-2/7 h-full">
      <n-scrollbar class="h-full">
        <n-card :bordered="false" class="h-full">
          <n-tree key-field="routeId" label-field="routeNm" selectable :data="routeDataList" :node-props="nodeProps"></n-tree>
        </n-card>
      </n-scrollbar>
    </div>
    <div class="w-5/7 flex flex-col gap-y-3 h-full">
      <n-card :bordered="false">
        <n-form
          label-align="left"
          label-placement="left"
          label-width="auto"
          :inline="true"
          :model="formParams"
          :show-feedback="false"
          :show-require-mark="false"
        >
          <n-grid responsive="screen" cols="1 s:1 m:2 l:3 xl:4 2xl:4" :collapsed="isCollapse" :x-gap="16" :y-gap="16">
            <n-form-item-gi label="权限名称"> <n-input v-model:value="formParams.permNm" placeholder="请输入权限名称" /> </n-form-item-gi>
            <n-form-item-gi label="权限标签"> <n-input v-model:value="formParams.permLbl" placeholder="请输入权限标签" /> </n-form-item-gi>
            <n-form-item-gi label="权限描述"> <n-input v-model:value="formParams.permDsc" placeholder="请输入权限描述" /> </n-form-item-gi>
            <n-gi :suffix="true">
              <n-space align="center" justify="end">
                <n-button
                  v-if="hasPermission('bmpch:route:tree:perm:search', '查询路由权限管理列表')"
                  type="primary"
                  :loading="searchBtnLoading"
                  @click="handleSearch"
                >
                  <template #icon>
                    <n-icon>
                      <SearchOutlined />
                    </n-icon>
                  </template>
                  查询
                </n-button>
                <n-button @click="() => (formParams = new FormParams())">重置</n-button>
                <n-button type="primary" icon-placement="right" text @click="() => (isCollapse = !isCollapse)">
                  <template #icon>
                    <n-icon size="14" v-if="isCollapse">
                      <DownOutlined />
                    </n-icon>
                    <n-icon size="14" v-else>
                      <UpOutlined />
                    </n-icon>
                  </template>
                  {{ isCollapse ? '展开' : '收起' }}
                </n-button>
              </n-space>
            </n-gi>
          </n-grid>
        </n-form>
      </n-card>
      <n-card :bordered="false" class="flex-1">
        <DataTable
          remote
          striped
          :row-key="(row: BMPCH.RoutePermQryOutput_RoutePermDto) => row.permId"
          :columns="tableColumns"
          :data="dataList"
          :pagination="pagination"
          :loading="dataLoading"
          :scroll-x="1600"
          @update:page="updatePage"
          @update:page-size="updatePageSize"
          @reload="loadData"
        >
          <template #title>
            <n-space align="center">
              <n-button v-if="hasPermission('bmpch:route:tree:perm:add', '新建路由权限')" type="primary" @click="handleAdd">
                <template #icon>
                  <n-icon>
                    <PlusOutlined />
                  </n-icon>
                </template>
                新建
              </n-button>
            </n-space>
          </template>
        </DataTable>
        <Edit v-model:show="showModal" :biz-id="bizId" @refresh="loadData" />
      </n-card>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { h, reactive, ref, onMounted } from 'vue';
import { NSpace, NIcon, NButton, NInputNumber, NPopconfirm } from 'naive-ui';
import type { TreeOption, DataTableColumns } from 'naive-ui';
import { removeEmptyField } from '@yanfan/common/utils';
import DataTable, { getDefaultPagination } from '@/components/DataTable';
import type * as BMPCH from '@yanfan/bmpch-tsapi/types';
import { routeQry001, routePermQry, routePermRmv, routePermOrdrNumUpd } from '@yanfan/bmpch-tsapi/route';
import { DownOutlined, UpOutlined, SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, SortAscendingOutlined } from '@vicons/antd';
import { usePermission } from '@yanfan/common/hooks';
import Edit from './Edit.vue';

defineOptions({
  name: 'BmpchRoutePermList',
  titl: '路由权限管理列表',
});

const { hasPermission } = usePermission();

class FormParams {
  permNm: string | null = null;
  permLbl: string | null = null;
  routeId: string | null = null;
}

const tableColumns: DataTableColumns<BMPCH.RoutePermQryOutput_RoutePermDto> = [
  {
    title: '权限名称',
    key: 'permNm',
    width: 260,
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: '权限标签',
    key: 'permLbl',
    width: 300,
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: '权限描述',
    key: 'permDsc',
    width: 350,
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: '排序',
    key: 'ordrNum',
    width: 160,
    align: 'right',
    render(row) {
      return h(
        NPopconfirm,
        {
          onUpdateShow: (show) => {
            if (show) {
              ordrNum.value = row.ordrNum;
            }
          },
          onPositiveClick: () => {
            if (ordrNum.value === null) {
              window.$message.warning('排序号不能为空');
              return;
            }
            routePermOrdrNumUpd({ permId: row.permId, ordrNum: ordrNum.value }).then(() => {
              loadData();
            });
          },
        },
        {
          icon: () => h(NIcon, { size: 18 }, () => h(SortAscendingOutlined)),
          default: () => h(NInputNumber, { value: ordrNum.value, onUpdateValue: (value) => (ordrNum.value = value) }),
          trigger: () =>
            h(
              NButton,
              { text: true, iconPlacement: 'right' },
              { icon: () => h(NIcon, { size: 18 }, () => h(EditOutlined)), default: () => row.ordrNum },
            ),
        },
      );
    },
  },
  {
    title: '备注',
    key: 'rmrk',
    ellipsis: {
      tooltip: true,
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 140,
    align: 'center',
    fixed: 'right',
    render(row) {
      return h(NSpace, { align: 'center', justify: 'center' }, () => [
        h(
          NButton,
          { type: 'info', text: true, onClick: () => handleEdit(row) },
          { icon: () => h(NIcon, { size: 18 }, () => h(EditOutlined)), default: () => '编辑' },
        ),
        h(
          NPopconfirm,
          { onPositiveClick: () => handleDelete(row) },
          {
            trigger: () =>
              h(NButton, { type: 'error', text: true }, { icon: () => h(NIcon, { size: 18 }, () => h(DeleteOutlined)), default: () => '删除' }),
            default: () => '确定要删除该数据吗？',
          },
        ),
      ]);
    },
  },
];

const showModal = ref(false);
const isCollapse = ref(false);
const formParams = ref(new FormParams());
const searchBtnLoading = ref(false);
const bizId = ref<string | null>(null);
const ordrNum = ref<number | null>(0);
const pagination = reactive(getDefaultPagination());
const dataLoading = ref(false);
const dataList = ref<BMPCH.RoutePermQryOutput_RoutePermDto[]>([]);
const routeDataList = ref<BMPCH.RouteQry001Output_RouteDto[]>([]);

onMounted(() => {
  loadRouteData();
});

function updatePage(page: number) {
  pagination.page = page;
  loadData();
}

function updatePageSize(pageSize: number) {
  pagination.page = 1;
  pagination.pageSize = pageSize;
  loadData();
}

function loadData() {
  if (!formParams.value.routeId) {
    window.$message.warning('请选择路由');
    return;
  }
  dataLoading.value = true;
  routePermQry({ pageIndx: pagination.page, pageSize: pagination.pageSize, ...removeEmptyField(formParams.value) })
    .then((data) => {
      dataList.value = data.list;
      pagination.itemCount = data.totl;
    })
    .finally(() => {
      dataLoading.value = false;
      searchBtnLoading.value = false;
    });
}

function handleSearch() {
  searchBtnLoading.value = true;
  pagination.page = 1;
  loadData();
}

function handleAdd() {
  bizId.value = String();
  showModal.value = true;
}

function handleEdit(row: BMPCH.RoutePermQryOutput_RoutePermDto) {
  bizId.value = row.permId;
  showModal.value = true;
}

function handleDelete(row: BMPCH.RoutePermQryOutput_RoutePermDto) {
  routePermRmv({ permId: row.permId }).then(() => {
    window.$message.success('删除成功');
    loadData();
  });
}

function loadRouteData() {
  routeQry001({ ...removeEmptyField(formParams.value) }).then((data) => {
    routeDataList.value = data.list;
    handleLeafNode(null, routeDataList.value);
  });
}

function handleLeafNode(parent: BMPCH.RouteQry001Output_RouteDto | null, nodes: Array<any>) {
  nodes.map((node) => {
    node.parent = parent;
    if (node.children && node.children.length === 0) {
      node.isLeaf = true;
    } else {
      handleLeafNode(node, node.children);
    }
  });
}

function nodeProps({ option }: { option: TreeOption }) {
  return {
    onClick() {
      formParams.value.routeId = String(option.routeId);
      loadData();
    },
  };
}
</script>

<style lang="scss" scoped></style>
